package com.ai.controller;

import com.ai.entity.MergeRequest;
import com.ai.entity.UploadResponse;
import com.ai.service.FileUploadService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file/upload")
@Slf4j
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 上传文件分片
     */
    @PostMapping("/chunk")
    public ResponseEntity<?> uploadChunk(
            @RequestParam("chunk") MultipartFile chunk,
            @RequestParam("hash") String hash,
            @RequestParam("index") Integer index,
            @RequestParam("fileHash") String fileHash,
            @RequestParam("chunkSize") Integer chunkSize,
            @RequestParam(value = "fileName", required = false) String fileName) {

        // 基本参数验证
        if (chunk == null || chunk.isEmpty()) {
            return ResponseEntity.badRequest().body(UploadResponse.error("分片文件不能为空"));
        }

        if (hash == null || hash.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(UploadResponse.error("分片哈希不能为空"));
        }

        if (index == null || index < 0) {
            return ResponseEntity.badRequest().body(UploadResponse.error("分片索引无效"));
        }

        if (fileHash == null || fileHash.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(UploadResponse.error("文件哈希不能为空"));
        }

        try {
            UploadResponse response = fileUploadService.uploadChunk(
                    chunk, hash, index, fileHash, chunkSize, fileName);

            if (response.isSuccess()) {
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("上传文件分片时发生错误: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                    .body(UploadResponse.error("服务器内部错误: " + e.getMessage()));
        }
    }

    /**
     * 合并文件分片
     */
    @PostMapping("/merge")
    public ResponseEntity<?> mergeChunks(@Valid @RequestBody MergeRequest request) {
        try {
            UploadResponse response = fileUploadService.mergeChunks(
                    request.getFileHash(),
                    request.getFileName(),
                    request.getTotalChunks(),
                    request.getChunkSize()
            );

            if (response.isSuccess()) {
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("合并文件时发生错误: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                    .body(UploadResponse.error("合并文件时发生错误: " + e.getMessage()));
        }
    }

    /**
     * 检查文件状态
     */
    @GetMapping("/check")
    public ResponseEntity<?> checkFileStatus(@RequestParam String fileHash, @RequestParam String fileName, @RequestParam Integer totalChunks) {

        if (fileHash == null || fileHash.trim().isEmpty()) {
            return ResponseEntity.badRequest().body(UploadResponse.error("文件哈希不能为空"));
        }
        if (totalChunks == null || totalChunks < 0) {
            return ResponseEntity.badRequest().body(UploadResponse.error("分片数量无效"));
        }

        try {
            UploadResponse response = fileUploadService.checkFileStatus(fileHash, fileName, totalChunks);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("检查文件状态时发生错误: {}", e.getMessage(), e);
            return ResponseEntity.internalServerError()
                    .body(UploadResponse.error("检查文件状态时发生错误: " + e.getMessage()));
        }
    }

    /**
     * 获取上传配置信息
     */
    @GetMapping("/config")
    public ResponseEntity<Map<String, Object>> getUploadConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("maxChunkSize", 5 * 1024 * 1024); // 5MB
        config.put("maxFileSize", 10L * 1024 * 1024 * 1024); // 10GB
        config.put("supportedTypes", new String[]{"*"});
        return ResponseEntity.ok(config);
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, String>> healthCheck() {
        Map<String, String> response = new HashMap<>();
        response.put("status", "UP");
        response.put("service", "File Upload Service");
        return ResponseEntity.ok(response);
    }
}
